package com.zhuhjay.common.netty.config;

import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.corundumstudio.socketio.listener.ExceptionListener;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ZhuHJay
 * @date 2023/7/10 9:58
 */
@Configuration
public class NettySocketIoConfig {

    @Bean
    @ConfigurationProperties(prefix = "socketio.server")
    public com.corundumstudio.socketio.Configuration socketIoConfig(
            AuthorizationListener authorizationListener,
            ExceptionListener exceptionListener
            /*RedissonClient redissonClient*/
    ) {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        // 身份认证
        config.setAuthorizationListener(authorizationListener);
        // 异常监听
        config.setExceptionListener(exceptionListener);
        // 设置 redisson 作为 socketio 的存储
        //config.setStoreFactory(new RedissonStoreFactory(redissonClient));
        return config;
    }

    @Bean(destroyMethod = "stop")
    public SocketIOServer socketServer(com.corundumstudio.socketio.Configuration socketIoConfig) {
        return new SocketIOServer(socketIoConfig);
    }

    /**
     * 用于扫描 netty-socketio 的注解，比如 @OnConnect、@OnEvent
     */
    //@Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        return new SpringAnnotationScanner(socketServer);
    }

    @Bean
    public ApplicationRunner socketRunner(SocketIOServer socketServer) {
        return args -> {
            // 用于关闭服务的钩子
            Runtime.getRuntime().addShutdownHook(new Thread(socketServer::stop));
            socketServer.start();
        };
    }

}
